import path from 'path'
import fs from 'fs'
const Base = require('../base.js');

module.exports = class extends Base {
	getFile (dir, type, fileName) {
		const imageDir = dir === 'temp' ? 'imageTempDir' : 'imageDir'
		this.download(path.resolve(process.cwd(), this.config(imageDir), type, fileName))
	}
	uploadAction() {
		const file = this.file('image')
		if (!file) {
			this.fail(1, '请上传图片')
		}
		const imageDir = path.resolve(process.cwd(), this.config('imageTempDir'))
		const tempPath = file.path
		const fileName = `${tempPath.substr(tempPath.lastIndexOf('upload_') + 7)}${file.name.substr(file.name.lastIndexOf('.'))}`
		const image = this.images(tempPath)
		const original = path.resolve(imageDir, 'original')
		const pc = path.resolve(imageDir, 'pc')
		const mobile = path.resolve(imageDir, 'mobile')
		const thumbnail = path.resolve(imageDir, 'thumbnail')
		if (!fs.existsSync(imageDir)) {
			this.mkdir(original)
			this.mkdir(pc)
			this.mkdir(mobile)
			this.mkdir(thumbnail)
		}
    image.save(path.resolve(original, fileName))
    image.size(600).save(path.resolve(pc, fileName))
    image.size(300).save(path.resolve(mobile, fileName))
    image.size(100).save(path.resolve(thumbnail, fileName))
		this.success({
      original_img: `/temp/original/${fileName}`,
      m_img: `/temp/mobile/${fileName}`,
      pc_img: `/temp/pc/${fileName}`,
      thumbnail: `/temp/thumbnail/${fileName}`
		})
	}
	originalAction () {
		const {dir, file} = this.get()
		this.getFile(dir, 'original', file)
  }
  thumbnailAction () {
	  const {dir, file} = this.get()
	  this.getFile(dir, 'thumbnail', file)
  }
  mobileAction () {
	  const {dir, file} = this.get()
	  this.getFile(dir, 'mobile', file)
  }
  pcAction () {
	  const {dir, file} = this.get()
	  this.getFile(dir, 'pc', file)
  }
};
